<template>
    <el-dialog :title="currentRoute?'编辑线路':'添加线路'" :visible.sync="showDialog_" custom-class='dialog_right dialogScroll_add MkAddRoute ' top="0%" @close='closeDialog("addForm")' @open='openDialog'>
      <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight -200)+'px'}]">
        <el-form :model="addForm.formItem" :rules="addForm.rules" ref="addForm" label-width="80px">
          <input type="text" style="display:none" />
          <el-form-item  label="乘车车站" prop='startSiteId'>
            <el-select v-model="addForm.formItem.startSiteId"  filterable placeholder='请选择乘车车站（必选）' @change="changeSite">
                <el-option v-for='item in siteSelect' :label="item.name" :value="item.id+'_'+item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  label="终点站" prop='endSiteId'>
            <el-select v-model="addForm.formItem.endSiteId" filterable  @change="changeSite"  placeholder='请选择终点站（必选）'>
              <el-option v-for='item in siteSelect' :label="item.name" :value="item.id+'_'+item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item  label="途经站" prop='passSiteArr'>
            <el-select v-model="addForm.formItem.passSiteArr" @change="changeSite" multiple placeholder='请选择途经站'>
              <el-option v-for='item in siteSelect' :label="item.name" :value="item.id+'_'+item.name" :key="item.id"></el-option>
            </el-select>
          </el-form-item>


          <el-form-item  label="关联车辆" prop='busIdArr'>
            <el-select v-model="addForm.formItem.busIdArr" multiple placeholder='请选择关联车辆' @change="changeBus">
              <el-option v-for='item in carSelect' :label="item.plateNumber" :value="item.id+'_'+item.seatCounts" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item  label="票数" prop='totalTicket'>
            <el-input v-model="addForm.formItem.totalTicket"  placeholder='请输入票数（必填）'></el-input>
          </el-form-item>

          <template v-if="addForm.formItem.startSiteId && addForm.formItem.endSiteId">
            <div style = 'padding-top:20px;margin-top:20px;border-top:1px solid #f0f3f6;'>票价及说明</div>
            <div style='margin-top:20px;color:#ff4949;' v-if="!renderPriceInfo">乘车车站不能与终点站一样，途经站不应该包含乘车车站和终点站，请调整</div>
            <table class="tabStyle" v-if="renderPriceInfo">
              <thead>
              <tr>
                <td>乘车车站</td>
                <td>到达车站</td>
                <td style="width:76px;">距离(公里)</td>
                <td style="width:76px;">耗时(小时)</td>
                <td style="width:64px;">票价(元)</td>
              </tr>
              </thead>
              <tbody>
              <template v-for="(item,index) in priceInfoArr">
                <tr>
                  <td>{{item.startSiteName}}</td>
                  <td>{{item.endSiteName}}</td>
                  <td><input type="text" :ref="'column_distance_'+index" @blur="checkDistance(index)" class="inputStyle inputStyleTime"></td>
                  <td><input type="text" :ref="'column_time_'+index" @blur="checkTime(index)" class="inputStyle inputStyleTime"></td>
                  <td><input type="text" :ref="'column_price_'+index" @blur="checkPrice(index)" class="inputStyle inputStylePrice" placeholder="必填"></td>
                </tr>
              </template>
              </tbody>
            </table>
          </template>
        </el-form>
      </el-scrollbar>
      <div slot="footer" class="dialog-footer footerStyle">
          <el-button type="primary"  class='btn-primary' :disabled = 'isSubmitBtnDisabled' @click='submitForm("addForm")' v-loading.fullscreen.lock="fullscreenLoading">保存</el-button>
          <el-button  type='primary' class="btn-cancel" :disabled = "isSubmitBtnDisabled"  @click="showDialog_ = false" size=''>取消</el-button>
      </div>
    </el-dialog>
</template>

<script>
import routeService from '../../../services/route'
import { mapState } from 'vuex'
export default {
  name: 'MkAddRoute',
  components: {

  },
  props: ['showDialog','currentRoute'],
  computed: mapState({
    bodyHeight: state => state.global.bodyHeight,
    siteSelect: state => state.route.siteList,
    carSelect: state => state.route.allCarList
  }),
  mounted:function() {
    this.$store.dispatch('loadAllCars',{fields:'id,number,plateNumber,seatCounts'})
  },
  methods: {
    checkDistance(index) {
      var reg=/^(0|[1-9]{1}\d{0,4})(\.{1}[0-9]{1})?$/;
      var value = (this.$refs['column_distance_' + index][0].value + '').trim();
      if (!reg.test(value) && value != '') {
        this.$message.warning('请输入数字，整数最多5位，小数最多1位');
        this.$refs['column_distance_' + index][0].focus();
        return;
      }
    },
    checkPrice(index) {
      var value = (this.$refs['column_price_' + index][0].value).trim();
      var reg = /^(0|[1-9]{1}\d{0,8})(\.{1}[0-9]{1,2})?$/;
      if (!reg.test(value) && value != '') {
        this.$message.warning('请输入正确的格式，最多4位整数，2位小数');
        this.$refs['column_price_' + index][0].focus();
        return;
      }
    },
    checkTime(index) {
      var reg=/^(0|[1-9]{1}\d{0,3})(\.{1}[0-9]{1})?$/;
      var value = (this.$refs['column_time_' + index][0].value + '').trim();
      if (!reg.test(value) && value != '') {
        this.$message.warning('请输入数字，整数最多4位，小数最多1位');
        this.$refs['column_time_' + index][0].focus();
        return;
      }
    },
    changeSite() {
      let form = this.addForm.formItem;
      this.renderPriceInfo = true;
      if(form.passSiteArr.indexOf(form.startSiteId) > -1 ||  form.passSiteArr.indexOf(form.endSiteId) > -1){
        this.renderPriceInfo = false;
      }
      if(form.startSiteId == form.endSiteId) {
        this.renderPriceInfo = false;
      }
      if(form.startSiteId && form.endSiteId){
        let arr = [];
          if(form.passSiteArr.length>0) {
            form.passSiteArr.forEach((item,index) => {
                arr.push({
                  startSiteId: form.startSiteId.split('_')[0],
                  endSiteId: item.split('_')[0],
                  siteType:'Midway',
                  sort:index + 1,

                  startSiteName: form.startSiteId.split('_')[1],
                  endSiteName: item.split('_')[1],
                })
            })
          }
         arr.push({
          startSiteId: form.startSiteId.split('_')[0],
          endSiteId: form.endSiteId.split('_')[0],
          siteType:'End',
          sort:form.passSiteArr.length + 1,

          startSiteName: form.startSiteId.split('_')[1],
          endSiteName: form.endSiteId.split('_')[1],
        });
        this.priceInfoArr  = arr;
      }
    },
    changeBus() {
      let arr = this.addForm.formItem.busIdArr;
      let count = 0;
      arr.forEach((item) => {
          count += parseInt(item.split('_')[1]);
      })
      this.addForm.formItem.totalTicket = count+'';
    },
    closeDialog(formName) {
      this.$refs[formName].resetFields();
      this.$emit('closeDialog',this.isRefresh);
    },
    openDialog() {
      this.isRefresh = 'no';
      this.isSubmitBtnDisabled = false;
      if(this.currentRoute) {
        let form = this.addForm.formItem;
        let currentRoute = this.currentRoute;
        form.endSiteId = currentRoute.endSite.id+'_'+currentRoute.endSite.name;
        form.startSiteId = currentRoute.midwayLines[0].startSite.id+'_'+currentRoute.midwayLines[0].startSite.name;
        let passSiteArr = [];
        currentRoute.midwayLines.forEach((item)=>{
            if(item.siteType == 'Midway') {
              passSiteArr.push(item.endSite.id+'_'+item.endSite.name)
            }
        });
        form.passSiteArr = passSiteArr;

        let busArr = [];
        currentRoute.buses.forEach((item)=>{
          busArr.push(item.id+'_'+item.seatCounts)
        });
        form.busIdArr = busArr;

        this.changeSite();
        this.changeBus();
        this.$nextTick(function() {
          currentRoute.midwayLines.forEach((item,index) => {
            this.$refs['column_distance_'+index][0].value = item.distance;
            this.$refs['column_time_'+index][0].value = item.time;
            this.$refs['column_price_'+index][0].value = item.price;
          })
          form.totalTicket = currentRoute.totalTicket;
        })
      }
    },
    submitForm(formName){
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let form = this.addForm.formItem;
          let param ={
            busIds: form.busIdArr.map((item) => item.split('_')[0]).join(','),
            distance: '',
            endSiteId: form.endSiteId.split('_')[0],
            midwayLines: '',
            prices: '',
            startSiteId: form.startSiteId.split('_')[0],
            time: '',
            totalTicket: form.totalTicket,
          };

//         处理票价信息数据
          let ticketArr = [];
          for(let i=0;i<this.priceInfoArr.length;i++) {
            let item = this.priceInfoArr[i];
            let price = this.$refs['column_price_' + i][0].value.trim();
            let time = this.$refs['column_time_' + i][0].value.trim();
            let distance = this.$refs['column_distance_' + i][0].value.trim();

            if(price.trim() == '') {
              this.$message.warning('请填写票价');
              return;
            }
            if(item.siteType == 'End') {
                param.time = time;
                param.prices = price;
                param.distance = distance;
            }
            ticketArr.push({
              startSiteId:item.startSiteId,
              endSiteId: item.endSiteId,
              siteType:item.siteType,
              distance:distance,
              time: time,
              price: price,
              sort: item.sort,
            })
          }
          param.midwayLines = JSON.stringify(ticketArr);
console.log(JSON.stringify(param))
          this.fullscreenLoading = true;
          this.isSubmitBtnDisabled = true;
          if(this.currentRoute) {
            param.id = this.currentRoute.id;
            routeService.editLine(param,(data)=>{
              this.$message.success('编辑成功');
              this.isRefresh = 'yes';
              this.showDialog_ = false;
              this.fullscreenLoading = false;
            },(data)=>{
              this.fullscreenLoading = false;
              this.isSubmitBtnDisabled = false;
            })
          }else{
            routeService.addLine(param,(data)=>{
              this.$message.success('添加成功');
              this.isRefresh = 'yes';
              this.showDialog_ = false;
              this.fullscreenLoading = false;
            },(data)=>{
              this.fullscreenLoading = false;
              this.isSubmitBtnDisabled = false;
            })
          }
        }
      })
    }
  },
  watch: {
    showDialog: function(value) {
      this.showDialog_=value;
    }
  },
  data () {
    let validateTotalTicket = (rule,val,callback) => {
      if(val == '') {
        callback("请输入票数");
      }else{
        let  reg = /(^0$|^[1-9]{1}[0-9]*$)/;
        if(!reg.test(val)) {
          callback('请输入数字');
        }else{
          callback();
        }
      }
    }
    let validatePassSiteArr = (rule,val,callback) => {
      let form = this.addForm.formItem;
      if(val.indexOf(form.startSiteId)>-1){
        callback('途经站不应该包含乘车站');
      }else if(val.indexOf(form.endSiteId)>-1){
        callback('途经站不应该包含终点站');
      }else{
        callback();
      }
    }
    let validateStartSiteId = (rule,val,callback) => {
      if(!val) {
          callback('请选择乘车站');
      }else if(val == this.addForm.formItem.endSiteId){
        callback('乘车车站不能与终点站相同，请重新选择');
      }else{
        callback();
      }
    }
    let validateEndSiteId = (rule,val,callback) => {
      if(!val) {
        callback('请选择终点站');
      }else if(val == this.addForm.formItem.startSiteId){
        callback('终点站不能与乘车车站相同，请重新选择');
      }else{
        callback();
      }
    }
    return {
      isSubmitBtnDisabled: false,
      fullscreenLoading: false,
      isRefresh: 'no',
      showDialog_: this.showDialog,
      priceInfoArr: [],
      renderPriceInfo: true,
      addForm: {
        formItem: {
          startSiteId: '',
          endSiteId: '',
          totalTicket: '',
          busIds: '',

          busIdArr: [],
          passSiteArr: [],
        },
        rules: {
          startSiteId: {validator:validateStartSiteId,trigger:'change,blur'},
          endSiteId: {validator:validateEndSiteId,trigger:'change,blur'},
          totalTicket:{validator:validateTotalTicket,trigger:'change'},
          passSiteArr: {validator:validatePassSiteArr,trigger:'change'},
        }
      }

    }
  }
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang='less'>
 @import '../../../assets/style/main.less';
  .MkAddRoute{
    .addNode{
      color:@creatButton;
      cursor: pointer;
      &:hover{
        .my-opacity(0.8);
      }
    }
    .tabStyle{
      border-collapse:collapse;
      width:100%;
      box-sizing:border-box;
      border:1px solid #dfecec;
      margin-top:10px;
      line-height: 36px;
      text-align: center;
      thead{
        td{
          border:1px solid #dfecec;
          background:@borderColor;
          color:@fontColorThree;
          /*  border:1px solid @fontColorThree;*/
        }
      }
      tbody{
        line-height: 46px;
        td{
          border-left:1px solid #dfecec;
          border-bottom:1px solid #dfecec;
        }

      }
     .inputStyle{
       border:none;
       background:@borderColor;
       height:40px !important;
       margin:2px;
       outline: none;
      }
      .inputStylePrice{
        max-width:60px;
      }
      .inputStyleTime{
        max-width:70px;
      }
    }
  }
</style>
